<template>
  <GlobalDrawer
    v-model="visible"
    :title="formTitle"
    size="80%"
    :show-footer-buttons="true"
    @confirm="handleSubmit"
  >
    <el-form ref="formRef" :model="form" :rules="rules" label-width="100px" v-loading="loading">
      <el-form-item label="客户" prop="customer_id">
        <el-select
          v-model="form.customer_id"
          placeholder="请选择客户"
          filterable
          style="width: 100%"
        >
          <el-option
            v-for="item in customerOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="订单类型" prop="order_type">
        <el-select v-model="form.order_type" placeholder="请选择订单类型" style="width: 100%">
          <el-option
            v-for="item in typeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="订单标题" prop="title">
        <el-input v-model="form.title" placeholder="请输入订单标题" />
      </el-form-item>

      <el-form-item label="订单金额" prop="amount">
        <el-input-number v-model="form.amount" :min="0" :precision="2" style="width: 100%" />
      </el-form-item>

      <el-form-item label="合同编号">
        <el-input v-model="form.contract_no" placeholder="请输入合同编号" />
      </el-form-item>

      <el-form-item label="付款方式" prop="payment_type">
        <el-select v-model="form.payment_type" placeholder="请选择付款方式" style="width: 100%">
          <el-option
            v-for="item in paymentMethodOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="付款计划">
        <el-input
          v-model="form.payment_plan"
          type="textarea"
          :rows="2"
          placeholder="请输入付款计划，如：首付30%，尾款70%"
        />
      </el-form-item>

      <el-form-item label="订单描述">
        <el-input
          v-model="form.description"
          type="textarea"
          :rows="4"
          placeholder="请输入订单描述"
        />
      </el-form-item>

      <el-form-item label="合同文件">
        <el-upload
          ref="uploadRef"
          action=""
          :auto-upload="false"
          :on-change="handleFileChange"
          :on-remove="handleFileRemove"
          :file-list="form.contract_files"
          multiple
          accept=".pdf,.doc,.docx,.jpg,.jpeg,.png"
          list-type="picture-card"
        >
          <el-icon><Plus /></el-icon>
          <template #file="{ file }">
            <div>
              <img
                v-if="file.url && isImage(file.name)"
                :src="file.url"
                alt="文件预览"
                class="el-upload-list__item-thumbnail"
              />
              <el-icon v-else class="el-upload-list__item-icon"><Document /></el-icon>
              <span class="el-upload-list__item-name">{{ file.name }}</span>
              <el-button type="text" size="small" @click.stop="previewFile(file)">预览</el-button>
              <el-button type="text" size="small" @click.stop="removeFile(file)">删除</el-button>
            </div>
          </template>
        </el-upload>
      </el-form-item>
    </el-form>
  </GlobalDrawer>
</template>

<script setup lang="ts">
  import { ref, reactive, computed, watch } from 'vue'
  import { ElMessage, ElUpload } from 'element-plus'
  import { Plus, Document } from '@element-plus/icons-vue'
  import { orderApi, customerApi } from '@/api/crm'
  import type { Order } from '@/types/crm'
  import GlobalDrawer from '@/components/common/GlobalDrawer.vue'

  import type { UploadUserFile } from 'element-plus'

  const props = defineProps({
    modelValue: {
      type: Boolean,
      default: false,
    },
    orderId: {
      type: Number,
      default: 0,
    },
    customerId: {
      type: Number,
      default: 0,
    },
  })

  const emit = defineEmits(['update:modelValue', 'success'])

  const visible = computed({
    get: () => props.modelValue,
    set: value => emit('update:modelValue', value),
  })

  const formRef = ref()
  const uploadRef = ref<InstanceType<typeof ElUpload>>()
  const loading = ref(false)
  const submitting = ref(false)
  const specialOrderId = ref(0)
  const specialOrderFormVisible = ref(false)

  const form = reactive({
    customer_id: 0,
    order_type: 1,
    order_category: 1,
    title: '',
    amount: 0,
    contract_no: '',
    payment_type: 1,
    payment_plan: '',
    description: '',
    contract_files: [] as UploadUserFile[],
  })

  const rules = {
    customer_id: [{ required: true, message: '请选择客户', trigger: 'change' }],
    order_type: [{ required: true, message: '请选择订单类型', trigger: 'change' }],
    order_category: [{ required: true, message: '请选择订单类别', trigger: 'change' }],
    title: [{ required: true, message: '请输入订单标题', trigger: 'blur' }],
    amount: [{ required: true, message: '请输入订单金额', trigger: 'blur' }],
    payment_type: [{ required: true, message: '请选择付款方式', trigger: 'change' }],
  }

  const customerOptions = ref<Array<{ id: number; name: string }>>([])
  const typeOptions = ref<Array<{ value: string; label: string }>>([])
  const paymentMethodOptions = ref<Array<{ value: string; label: string }>>([])

  // 表单标题
  const formTitle = computed(() => {
    return props.orderId ? '编辑订单' : '新增订单'
  })

  // 获取订单详情
  const getOrderDetail = async () => {
    if (!props.orderId) return

    loading.value = true
    try {
      const res = await orderApi.detail(props.orderId)
      const data = res.data

      // 填充表单数据
      Object.keys(form).forEach(key => {
        if ((data as any)[key] !== undefined) {
          ;(form as any)[key] = (data as any)[key]
        }
      })
    } catch (error) {
      console.error('获取订单详情失败:', error)
    } finally {
      loading.value = false
    }
  }

  // 获取选项数据
  const getOptions = async () => {
    try {
      const [customerRes, typeRes, paymentMethodRes] = await Promise.all([
        customerApi.getCustomerOptions(),
        orderApi.typeOptions(),
        orderApi.getPaymentMethodOptions(),
      ])
      customerOptions.value = customerRes.data.map(
        (item: { value: string | number; label: string }) => ({
          id: item.value,
          name: item.label,
        })
      )
      typeOptions.value = typeRes.data
      paymentMethodOptions.value = paymentMethodRes.data
    } catch (error) {
      console.error('获取选项失败:', error)
    }
  }

  // 提交表单
  // 打开特殊订单表单
  const openSpecialOrderForm = () => {
    specialOrderId.value = props.orderId || 0
    specialOrderFormVisible.value = true
  }

  // 处理特殊订单表单提交成功
  const handleSpecialOrderSuccess = () => {
    specialOrderFormVisible.value = false
    emit('success')
    handleClose()
  }

  const handleSubmit = async () => {
    // 如果是特殊订单，不进行提交，由特殊订单表单处理
    if (form.order_category !== 1) {
      ElMessage.warning('请使用专用表单提交特殊订单')
      return
    }

    if (!formRef.value) return

    try {
      await formRef.value.validate()

      submitting.value = true

      // 创建FormData来处理文件上传
      const formData = new FormData()

      // 添加表单字段
      Object.keys(form).forEach(key => {
        if (key !== 'contract_files') {
          formData.append(key, (form as any)[key])
        }
      })

      // 添加合同文件
      form.contract_files.forEach((file: any) => {
        if (file.raw) {
          formData.append('contract_files[]', file.raw, file.name)
        }
      })

      // 添加其他固定字段
      formData.append('status', '1')
      formData.append('payment_status', '1')
      formData.append('contract_status', '1')
      formData.append('user_id', '1')

      if (props.orderId) {
        formData.append('id', props.orderId.toString())
        await orderApi.update(formData)
        ElMessage.success('编辑成功')
      } else {
        await orderApi.create(formData)
        ElMessage.success('新增成功')
      }

      emit('success')
      handleClose()
    } catch (error) {
      console.error('提交失败:', error)
    } finally {
      submitting.value = false
    }
  }

  // 判断是否为图片文件
  const isImage = (fileName: string): boolean => {
    const imageTypes = ['.jpg', '.jpeg', '.png', '.gif', '.bmp']
    const ext = fileName.toLowerCase().substring(fileName.lastIndexOf('.'))
    return imageTypes.includes(ext)
  }

  // 处理文件选择
  const handleFileChange = (file: any, fileList: any[]) => {
    form.contract_files = fileList
  }

  // 处理文件移除
  const handleFileRemove = (file: any, fileList: any[]) => {
    form.contract_files = fileList
  }

  // 预览文件
  const previewFile = (file: any) => {
    if (file.url) {
      window.open(file.url, '_blank')
    } else if (file.raw) {
      const fileUrl = URL.createObjectURL(file.raw)
      window.open(fileUrl, '_blank')
    }
  }

  // 删除文件
  const removeFile = (file: any) => {
    const index = form.contract_files.findIndex((item: any) => item.uid === file.uid)
    if (index !== -1) {
      form.contract_files.splice(index, 1)
    }
  }

  // 关闭对话框
  const handleClose = () => {
    // 重置表单
    if (formRef.value) {
      formRef.value.resetFields()
    }
    Object.keys(form).forEach(key => {
      if (key !== 'order_type' && key !== 'payment_type' && key !== 'customer_id') {
        ;(form as any)[key] = ''
      }
    })
    form.order_type = 1
    form.payment_type = 1
    form.customer_id = 0
    form.amount = 0
    form.order_category = 1
    form.contract_files = []

    visible.value = false
  }

  // 监听订单ID变化
  watch(
    () => props.orderId,
    newVal => {
      if (newVal) {
        getOrderDetail()
      }
    }
  )

  // 监听customerId变化
  watch(
    () => props.customerId,
    newVal => {
      if (newVal) {
        form.customer_id = newVal
      }
    }
  )

  // 监听对话框显示状态
  watch(visible, newVal => {
    if (newVal) {
      getOptions()
      if (props.orderId) {
        getOrderDetail()
      } else if (props.customerId) {
        form.customer_id = props.customerId
      }
    }
  })
</script>

<style scoped>
  .el-form {
    padding-right: 20px;
  }

  /* 抽屉底部按钮样式 */
  :deep(.global-drawer-footer .el-button--primary) {
    background-color: #67c23a !important;
    border-color: #67c23a !important;
    color: #ffffff !important;
  }
</style>
